package com.ias.log.service.impl;

import com.ias.log.model.OperationLog;
import com.ias.log.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;

/**
 * 日志服务默认实现
 * 如果业务系统没有提供自定义实现，则使用此默认实现
 * 
 * @author ias
 * @since 2024
 */
@Slf4j
@Service
@ConditionalOnMissingBean(LogService.class)
public class LogServiceImpl implements LogService {

    @Override
    public void save(OperationLog operationLog) {
        // 默认实现：仅打印日志到控制台
        // 业务系统应该提供自己的实现，将日志保存到数据库
        log.info("操作日志[默认实现] - {}", formatLog(operationLog));
    }

    @Override
    public String selectClientNameByClientId(String clientId) {
        // 默认返回clientId本身
        return clientId;
    }

    @Override
    public String selectServiceName(String serviceId) {
        // 默认返回serviceId本身
        return serviceId;
    }

    /**
     * 格式化日志信息
     */
    private String formatLog(OperationLog log) {
        return String.format(
                "TraceId=%s, 模块=%s, 操作=%s, 描述=%s, 用户=%s, IP=%s, 耗时=%dms, 状态=%s",
                log.getTraceId(),
                log.getModule(),
                log.getOptTypeName(),
                log.getRemark(),
                log.getUsername(),
                log.getIp(),
                log.getDuration(),
                log.getFlag() ? "成功" : "失败"
        );
    }
}

